﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;

namespace GoodStuff.Web.Controls
{
    /// <summary>
    /// Requires that at least on element of the checkboxlist is selected. Supports clientside validation.
    /// </summary>
  public class CheckBoxListRequiredFieldValidator : System.Web.UI.WebControls.BaseValidator 
   {
     private ListControl _listctrl;

     public CheckBoxListRequiredFieldValidator()
     {
         //base.EnableClientScript = false;
     }
 
     protected override bool ControlPropertiesValid()
     {
       Control ctrl = FindControl(ControlToValidate);
       
       if (ctrl != null) 
       {
           _listctrl = ctrl as ListControl;
         return (_listctrl != null);   
       }
       else 
         return false;  // raise exception
     }
 
     protected override bool EvaluateIsValid()
     {     
       return _listctrl.SelectedIndex != -1;
     }

     protected override void OnPreRender(EventArgs e)
     {
         base.OnPreRender(e);

         if (this.EnableClientScript)
         {
             // Register the client-side function using WebResource.axd (if needed)
             // see: http://aspnet.4guysfromrolla.com/articles/080906-1.aspx
             if (this.RenderUplevel && this.Page != null && !this.Page.ClientScript.IsClientScriptIncludeRegistered(this.GetType(), "goodStuffValidators"))
             {
                 string url = this.Page.ClientScript.GetWebResourceUrl(this.GetType(), "GoodStuff.Web.Controls.GoodStuffValidators.js");
                 ScriptManager.RegisterClientScriptInclude(this, this.GetType(), "goodStuffValidators", url);
             }
         }
     }


     protected override void AddAttributesToRender(HtmlTextWriter writer)
     {
         base.AddAttributesToRender(writer);

         if (this.EnableClientScript)
         {
             // Add the client-side code (if needed)
             if (this.RenderUplevel)
             {
                 // Indicate the mustBeChecked value and the client-side function to used for evaluation
                 // Use AddAttribute 
                 //if Helpers.EnableLegacyRendering is true; otherwise, use expando attributes
                 writer.AddAttribute("evaluationfunction", "CheckBoxListValidatorEvaluateIsValid", false);
                 //}
                 //else
                 //{
                 //    this.Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "CheckBoxListValidatorEvaluateIsValid", false);
                 //}
             }
         }
     }

   }
}

